package com.ruoyi.prod.service.impl;

import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.core.constant.HttpStatus;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.prod.domain.EsProd;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import com.ruoyi.common.core.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.prod.domain.TbBrand;
import com.ruoyi.prod.mapper.ProdMapper;
import com.ruoyi.prod.domain.Prod;
import com.ruoyi.prod.service.IProdService;

import javax.servlet.http.HttpServletRequest;

/**
 * 商品Service业务层处理
 * 
 * @author nz
 * @date 2025-08-09
 */
@Slf4j
@Service
public class ProdServiceImpl implements IProdService 
{
    @Autowired
    private ProdMapper prodMapper;
    @Autowired
    private ElasticsearchRestTemplate restTemplate;

    /**
     * 查询商品
     * 
     * @param prodId 商品主键
     * @return 商品
     */
    @Override
    public Prod selectProdByProdId(Long prodId)
    {
        return prodMapper.selectProdByProdId(prodId);
    }

    /**
     * 查询商品列表
     * 
     * @param prod 商品
     * @return 商品
     */
    @Override
    public List<Prod> selectProdList(Prod prod)
    {
        return prodMapper.selectProdList(prod);
    }

    /**
     * 新增商品
     * 
     * @param prod 商品
     * @return 结果
     */
    @Transactional
    @Override
    public int insertProd(Prod prod)
    {
        prod.setCreateTime(DateUtils.getNowDate());
        int rows = prodMapper.insertProd(prod);
        insertTbBrand(prod);
        return rows;
    }

    /**
     * 修改商品
     * 
     * @param prod 商品
     * @return 结果
     */
    @Transactional
    @Override
    public int updateProd(Prod prod)
    {
        prod.setUpdateTime(DateUtils.getNowDate());
        prodMapper.deleteTbBrandByBrandId(prod.getProdId());
        insertTbBrand(prod);
        return prodMapper.updateProd(prod);
    }

    /**
     * 批量删除商品
     * 
     * @param prodIds 需要删除的商品主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteProdByProdIds(Long[] prodIds)
    {
        prodMapper.deleteTbBrandByBrandIds(prodIds);
        return prodMapper.deleteProdByProdIds(prodIds);
    }

    /**
     * 删除商品信息
     * 
     * @param prodId 商品主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteProdByProdId(Long prodId)
    {
        prodMapper.deleteTbBrandByBrandId(prodId);
        return prodMapper.deleteProdByProdId(prodId);
    }

    @Override
    public TableDataInfo getEsProdList(Integer pageNum, Integer pageSize, Prod prod) {
        PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize);
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        if(StringUtils.isNotNull(prod.getProdName())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("prodName",prod.getProdName()));
        }
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<font color='red'>")
                .postTags("</font>")
                .field("prodName");
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        nativeSearchQueryBuilder.withHighlightBuilder(highlightBuilder)
                .withQuery(boolQueryBuilder)
                .withPageable(pageRequest);
        SearchHits<EsProd> search = restTemplate.search(nativeSearchQueryBuilder.build(), EsProd.class);
        long totalHits = search.getTotalHits();
        ArrayList<EsProd> esProds = new ArrayList<>();
        for (SearchHit<EsProd> esProdSearchHit : search) {
            EsProd content = esProdSearchHit.getContent();
            List<String> prodName = esProdSearchHit.getHighlightField("prodName");
            if(prodName.size()>0 && ObjectUtils.isNotEmpty(prodName)){
                content.setProdName(prodName.get(0));
            }
            esProds.add(content);
        }
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setMsg("查询成功");
        tableDataInfo.setTotal(totalHits);
        tableDataInfo.setCode(HttpStatus.SUCCESS);
        tableDataInfo.setRows(esProds);
        return tableDataInfo;
    }

    @Override
    public AjaxResult createIndex() {
        IndexOperations indexOperations = restTemplate.indexOps(EsProd.class);
        boolean exists = indexOperations.exists();
        if(exists){
            indexOperations.delete();
        }
        indexOperations.create();
        Document mapping = indexOperations.createMapping();
        indexOperations.putMapping(mapping);
        return AjaxResult.success("创建成功");
    }
    @Scheduled(cron = "0 */1 * * * *")
    @Override
    public AjaxResult getProdList() {
        Prod prod = new Prod();
        List<Prod> prods = prodMapper.selectProdList(prod);
        for (Prod prod1 : prods) {
            EsProd bean = BeanUtil.toBean(prod1, EsProd.class);
            restTemplate.save(bean);
            log.info("添加到es中成功！！！！！！！！");
        }
        return AjaxResult.success("同步数据成功!!!!!!!!!!!!!");
    }

    /**
     * 新增品牌信息
     * 
     * @param prod 商品对象
     */
    public void insertTbBrand(Prod prod)
    {
        List<TbBrand> tbBrandList = prod.getTbBrandList();
        Long prodId = prod.getProdId();
        if (StringUtils.isNotNull(tbBrandList))
        {
            List<TbBrand> list = new ArrayList<TbBrand>();
            for (TbBrand tbBrand : tbBrandList)
            {
                tbBrand.setBrandId(prodId);
                list.add(tbBrand);
            }
            if (list.size() > 0)
            {
                prodMapper.batchTbBrand(list);
            }
        }
    }
}
